<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="tabs">
      <div
        class="tabs-item"
        :class="{ active: currentTab === index }"
        v-for="(item, index) in tabs"
        :key="index"
        @click="handleChangeTab(item, index)"
      >
        {{ item }}
      </div>
    </div>
    <div class="body" v-show="currentTab === 0">
      <div class="body-left">
        <div class="project">
          <el-form
            :model="basicForm"
            label-position="top"
            :rules="basicRules"
            ref="basicFormRef"
          >
            <!-- 基本信息 -->
            <div class="project-part">
              <!-- <div class="project-part-title">基本信息</div> -->
              <!-- 统一的动态表单字段渲染 -->
              <template
                v-for="(group, gIndex) in groupedFormFields"
              >
                <div class="project-part-title">
                  {{ group[0].groupName }}
                </div>
                <!-- <el-row
                  v-for="(group, gIndex) in groupedFormFields"
                  :key="`form-${gIndex}`"
                > -->
                <el-row>
                  <el-col
                    v-for="field in group"
                    :key="field.key"
                    :span="8"
                  >
                    <el-form-item
                      :label="field.label"
                      :class="field.tag"
                      :prop="
                        field.required ? field.key : ''
                      "
                    >
                      <!-- input -->
                      <el-input
                        v-if="field.component === 'input'"
                        v-model="basicForm[field.key]"
                        :placeholder="'请输入'"
                        :type="field.type || 'text'"
                        :rows="
                          field.type === 'textarea'
                            ? field.rows || 3
                            : undefined
                        "
                        :disabled="
                          isFormItemDisabled(field)
                        "
                      />
                      <!-- select -->
                      <el-select
                        v-else-if="
                          field.component === 'select'
                        "
                        v-model="basicForm[field.key]"
                        clearable
                        :placeholder="'请选择'"
                        :disabled="isDetail"
                        :multiple="field.multiple"
                        :filterable="field.filterable"
                        :allow-create="field.allowCreate"
                        :popper-append-to-body="false"
                        @change="
                          handleFieldChange(
                            field.key,
                            $event
                          )
                        "
                      >
                        <!-- :disabled="isDetail || (field.key === 'socialCode' && isExisting)" -->
                        <el-option
                          v-for="(item, i) in getOptions(
                            field.optionsKey
                          )"
                          :key="
                            item.value
                              ? item.value +
                                (item.pkid ?? '')
                              : item
                          "
                          :label="
                            item.label ? item.label : item
                          "
                          :value="
                            item.value ? item.value : item
                          "
                        />
                      </el-select>
                      <!-- radio -->
                      <el-radio-group
                        v-else-if="
                          field.component === 'radio'
                        "
                        v-model="basicForm[field.key]"
                        :disabled="isDetail"
                      >
                        <el-radio
                          v-for="option in field.options"
                          :key="option"
                          :label="option"
                        >
                          {{ option }}
                        </el-radio>
                      </el-radio-group>
                      <!-- date -->
                      <el-date-picker
                        v-else-if="
                          field.component === 'date'
                        "
                        v-model="basicForm[field.key]"
                        type="date"
                        :disabled="isDetail"
                        placeholder="选择日期"
                      />
                      <!-- star -->
                      <StarSelect
                        v-else-if="
                          field.component === 'star'
                        "
                        v-model="basicForm[field.key]"
                        :disabled="isDetail"
                      />
                      <!-- cascader -->
                      <el-cascader
                        v-else-if="
                          field.component === 'cascader'
                        "
                        v-model="basicForm[field.key]"
                        :options="
                          getOptions(field.optionsKey)
                        "
                        :disabled="isDetail"
                        clearable
                        :placeholder="'请选择'"
                        :filterable="field.filterable"
                        :props="field.cascaderProps || {}"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>

              <!-- <attachmentFiles
                ref="attachmentRef"
                :detailData="basicForm"
                :fileList="basicForm.fileList"
                :pkid="basicForm.pkid"
                :type="isDetail ? 'detail' : 'edit'"
                @changeFile="changeFile"
                :canDaoChu="canDaoChu"
              /> -->
            </div>
          </el-form>
        </div>
      </div>

      <div class="body-right">
        <div class="project-part">
          <div class="top">
            <div class="project-part-title">进度信息</div>

            <el-button
              icon="el-icon-plus"
              @click="addProcess"
              class="add-btn"
              v-if="!isDetail"
              >新增进度</el-button
            >
          </div>
        </div>
        <ProgressInfo
          :isDetail="isDetail"
          :dataList="progressList"
          :stage="basicForm.stage"
          :key="`${editIndex}-${basicForm.stage}-${basicForm.property}-${progressList.length}`"
          @delete="deleteProgress"
          @edit="editProgress"
        ></ProgressInfo>
      </div>
    </div>
    <div class="body" v-show="currentTab === 1">
      <attachmentFiles
        ref="attachmentRef"
        :detailData="basicForm"
        :fileList="basicForm.fileList"
        :pkid="basicForm.pkid"
        :type="isDetail ? 'detail' : 'edit'"
        @changeFile="changeFile"
        :canDaoChu="canDaoChu"
      />
    </div>

    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>

    <ProgressDialog
      :visible.sync="showDialog"
      title="项目进展信息"
      :editIndex="editIndex"
      :currentData="currentData"
      :currentInfo="currentInfo"
      @confirm="handleSubmit"
      @resetEditIndex="resetEditIndex"
    />
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import {
  addInvestInfo,
  queryInvestInfoById,
  queryChainMasterOptions,
  queryConstructionProject,
  enterpriseInfoQuery,
  querySettledCarrier
} from '@/api/dataManagement'
import ProgressInfo from './components/progressInfo.vue'
import StarSelect from '@/components/starSelect'
import ProgressDialog from './components/addProgressDialog.vue'
import attachmentFiles from './components/attachmentFiles.vue'
import {
  projectStageOptions,
  industryTypeOptions,
  propertyOptions,
  industrialChainOptions,
  projectOriginalOptions,
  otherApplyImportantArea,
  isImportantProject,
  isFinancingProject,
  projectLevelOptions,
  otherIndustrialType,
  investTypeOptions,
  landingTypeOptions,
  projectStageTypeOptions
} from '@/utils/project/data'

import dayjs from 'dayjs'
import { cloneDeep } from 'lodash'
import { userQuery } from '@/api/user'

const DEPT_NAME = '投资促进部'

let instance = null
export default {
  props: {
    pkid: String,
    title: String,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Breadcrumb,
    ProgressInfo,
    StarSelect,
    ProgressDialog,
    attachmentFiles
  },
  data() {
    return {
      tabs: ['基本信息', '附件信息'],
      currentTab: 0,
      basicForm: {
        pkid: '',
        projectName: '',
        investmentTotal: '',
        investmentType: '', // 添加投资类型字段
        industryType: '',
        otherIndustryType: '',
        otherIndustryTypeDetail: '', // 添加所属产业链明细字段
        projectTopLevel: '',
        companyBackgroud: '',
        projectStarLevel: 0,
        content: '',
        stage: '',
        property: '', // 添加属性字段
        source: '',
        sourceContent: '',
        industryLink: '',
        otherIndustryLink: '',
        linkSource: '', // 添加链主来源字段
        contract: '',
        manager: '',
        financingFlag: '',
        padBusinessProjectProcessRelList: [],
        address: '',
        planBusinessFinishTime: '',
        planMeetTime: '',
        planSignTime: '',
        actuallySignTime: '',
        planInTime: '',
        actuallyInTime: '',
        importantFlag: '否',
        linkSourcePId: [],
        fixedInvestment: '',
        rdInvestment: '',
        landingArea: '',
        relatedProjectId: '',
        carrierArea: '',
        carrierName: '',
        peopleNum: '',
        remarks: '',
        landingType: '',
        hasForeignTrade: '',
        financing: '',
        telephone: '',
        settledCarrier: [],
        fileList: [],
        projectState: '',
        name: '',
        enterpriseId: '',
        socialCode: '',
        registerMoney: '',
        registerTime: '',
        valuation: '',
        productCategory: '',
        workingCapital: '',
        landRequirement: '',
        otherNeeds: '',
        estimatedOutput: '',
        floorHeight: '',
        load: '',
        hasFitment: '',
        hasRentFree: ''
      },
      basicRules: {
        projectName: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur'
          }
        ]
        // projectCode: [
        //   {
        //     required: true,
        //     message: '请输入项目编码',
        //     trigger: 'blur'
        //   }
        // ]
      },
      loading: false,
      isBasicFormReady: false,
      isBasicFormChanged: false,
      showBuyEquip: false,
      showTradeTarget: false,
      bb: '',
      bbOptions: [],
      progressList: [],
      props: { multiple: true },
      rating: 3,
      showDialog: false,
      input: '',
      value1: '',
      currentData: {
        createTime: '',
        stage: '',
        newestProcess: '',
        problemFlag: '是',
        problemContent: '',
        solveAdvice: ''
      },
      currentInfo: {
        stage: '',
        property: ''
      },
      editIndex: -1,
      chainMasterOptions: [], // 添加链主选项数据
      relatedProjectOptions: [], // 添加关联项目选项数据
      settledCarrierOptions: [], // 添加拟入驻载体选项数据
      enterpriseOptions: [],
      isExisting: false,
      // 统一的表单字段配置
      formFields: [
        // 第一行：项目名称、项目阶段、属性
        {
          groupName: '基本信息',
          label: '项目名称',
          key: 'projectName',
          component: 'input',
          required: true,
          visible: true
        },
        {
          groupName: '基本信息',
          label: '项目阶段',
          key: 'stage',
          component: 'select',
          optionsKey: 'projectStageOptions',
          visible: true
        },
        {
          groupName: '基本信息',
          label: '属性',
          key: 'property',
          component: 'select',
          optionsKey: 'propertyOptions',
          visible: true
        },

        // 第二行：是否认定为成都市重大项目 项目经理 项目星级
        {
          groupName: '基本信息',
          label: '是否认定为成都市重大项目',
          key: 'importantFlag',
          component: 'select',
          optionsKey: 'isImportantProject',
          visible: true
        },
        {
          groupName: '基本信息',
          label: '项目经理',
          key: 'manager',
          component: 'input',
          // component: 'select',
          // optionsKey: 'managerOptions',
          visible: true
        },
        {
          groupName: '基本信息',
          label: '项目星级',
          key: 'projectStarLevel',
          component: 'star',
          visible: true
        },
        // 产业类别
        // 第三行：项目来源、项目来源说明 链主/链属
        {
          groupName: '产业类别',
          label: '所属产业链',
          key: 'industryLink',
          component: 'select',
          optionsKey: 'industrialChainOptions',
          filterable: true,
          visible: true
        },
        {
          groupName: '产业类别',
          label: '所属产业链明细',
          key: 'otherIndustryTypeDetail',
          component: 'input',
          visible: true
        },
        {
          groupName: '产业类别',
          label: '链主/链属',
          key: 'linkSource',
          component: 'select',
          optionsKey: 'otherIndustrialType',
          visible: true
        },
        // {
        //   groupName: '产业类别',
        //   label: '关联链主企业',
        //   key: 'linkSourcePId',
        //   component: 'select',
        //   optionsKey: 'chainMasterOptions',
        //   multiple: true,
        //   filterable: true,
        //   visible: false // 动态计算
        // },
        {
          groupName: '产业类别',
          tag: 'new',
          label: '配套落地企业',
          key: 'productCategory',
          component: 'select',
          optionsKey: 'enterpriseOptions',
          multiple: true,
          filterable: true,
          visible: true
        },

        // 企业/投资方背景
        {
          groupName: '企业/投资方背景',
          tag: 'change',
          label: '企业/投资方全称', // '企业名称',
          key: 'name', // enterpriseId
          // component: 'input',
          component: 'select',
          optionsKey: 'enterpriseOptions',
          filterable: true,
          allowCreate: true,
          visible: true
        },
        {
          groupName: '企业/投资方背景',
          tag: 'new',
          label: '企业/投资方统一社会信用代码', // '企业名称',
          key: 'socialCode',
          component: 'input',
          visible: true
        },
        {
          groupName: '企业/投资方背景',
          label: '企业所在地',
          key: 'address',
          component: 'input',
          visible: true
        },
        {
          groupName: '企业/投资方背景',
          tag: 'change',
          label: '企业/投资方类型', // '项目能级',
          key: 'projectTopLevel',
          component: 'select',
          optionsKey: 'projectLevelOptions',
          multiple: true,
          visible: true
        },
        {
          groupName: '企业/投资方背景',
          tag: 'new',
          label: '成立时间',
          key: 'registerTime',
          component: 'date',
          visible: true
        },
        {
          groupName: '企业/投资方背景',
          tag: 'new',
          label: '注册资本',
          key: 'registerMoney',
          component: 'input',
          visible: true
        },
        {
          groupName: '企业/投资方背景',
          label: '估值',
          key: 'valuation',
          component: 'input',
          visible: true
        },
        {
          groupName: '企业/投资方背景',
          label: '企业联系人',
          key: 'contract',
          component: 'input',
          visible: true
        },
        {
          groupName: '企业/投资方背景',
          label: '联系方式',
          key: 'telephone',
          component: 'input',
          visible: true
        },
        {
          groupName: '企业/投资方背景',
          tag: 'change',
          label: '企业/投资方介绍', // '公司简介/投资方简介',
          key: 'companyBackgroud',
          component: 'input',
          type: 'textarea',
          visible: true
        },

        // 项目内容
        {
          groupName: '项目内容',
          label: '项目来源',
          key: 'source',
          component: 'select',
          optionsKey: 'projectOriginalOptions',
          visible: true
        },
        {
          groupName: '项目内容',
          label: '项目来源说明',
          key: 'sourceContent',
          component: 'input',
          visible: true
        },
        {
          groupName: '项目内容',
          label: '投资类型',
          key: 'investmentType',
          component: 'select',
          optionsKey: 'investTypeOptions',
          visible: true
        },
        {
          groupName: '项目内容',
          label: '总投资(亿元/亿美元)',
          key: 'investmentTotal',
          component: 'input',
          type: 'number',
          visible: true
        },
        {
          groupName: '项目内容',
          label: '固定资产投资(亿元)',
          key: 'fixedInvestment',
          component: 'input',
          type: 'number',
          visible: true
        },
        // 动态字段组：关联链主企业、投资类型、总投资
        {
          groupName: '项目内容',
          label: '研发投入(亿元)',
          key: 'rdInvestment',
          component: 'input',
          type: 'number',
          visible: true
        },
        {
          groupName: '项目内容',
          tag: 'new',
          label: '流动资金(亿元)', // 数字
          key: 'workingCapital',
          component: 'input',
          type: 'number',
          visible: true
        },
        {
          groupName: '项目内容',
          label: '是否产生外贸',
          key: 'hasForeignTrade',
          component: 'radio',
          options: ['是', '否'],
          visible: true
        },
        {
          groupName: '项目内容',
          tag: 'change',
          label: '落地内容', // '项目内容及诉求',
          key: 'content',
          component: 'input',
          type: 'textarea',
          visible: true
        },
        // {
        //   label: '产业类型',
        //   key: 'industryType',
        //   component: 'select',
        //   optionsKey: 'industryTypeOptions',
        //   visible: true
        // },

        // 项目诉求
        {
          groupName: '项目诉求',
          tag: 'new',
          label: '载体/用地需求',
          key: 'landRequirement',
          component: 'input',
          visible: true
        },
        {
          groupName: '项目诉求',
          label: '落地方式',
          key: 'landingType',
          component: 'select',
          optionsKey: 'landingTypeOptions',
          visible: true
        },
        {
          groupName: '项目诉求',
          label: '关联项目',
          key: 'relatedProjectId',
          component: 'select',
          optionsKey: 'relatedProjectOptions',
          filterable: true,
          visible: false // 动态计算
        },
        // 项目能级和落地方式相关
        {
          groupName: '项目诉求',
          label: '拿地面积(亩)',
          key: 'landingArea',
          component: 'input',
          visible: false // 动态计算
        },

        {
          groupName: '项目诉求',
          label: '拟入驻载体',
          key: 'settledCarrier',
          component: 'cascader',
          optionsKey: 'settledCarrierOptions',
          filterable: true,
          cascaderProps: {
            label: 'name',
            value: 'name',
            children: 'buildInfoList',
            expandTrigger: 'hover',
            emitPath: true, // 返回完整路径（包括父级）
            checkStrictly: false // 是否严格的遵守父子节点不互相关联
          },
          visible: false // 动态计算
        },
        {
          groupName: '项目诉求',
          label: '载体面积（平方米）',
          key: 'carrierArea',
          component: 'input',
          visible: false // 动态计算
        },
        {
          groupName: '项目诉求',
          tag: 'new',
          label: '层高（米）',
          key: 'floorHeight',
          component: 'input',
          type: 'number',
          visible: true
        },
        {
          groupName: '项目诉求',
          tag: 'new',
          label: '载重（吨）',
          key: 'load',
          component: 'input',
          type: 'number',
          visible: true
        },
        {
          groupName: '项目诉求',
          tag: 'new',
          label: '是否带装修',
          key: 'hasFitment',
          component: 'radio',
          options: ['是', '否'],
          visible: true
        },
        {
          groupName: '项目诉求',
          tag: 'new',
          label: '免租',
          key: 'hasRentFree',
          component: 'radio',
          options: ['是', '否'],
          visible: true
        },
        {
          groupName: '项目诉求',
          label: '拟入驻人数',
          key: 'peopleNum',
          component: 'input',
          type: 'number',
          visible: true
        },
        // 融资相关字段
        {
          groupName: '项目诉求',
          label: '融资规模(万元)',
          key: 'needMoney',
          component: 'input',
          type: 'number',
          visible: true
        },
        {
          groupName: '项目诉求',
          label: '是否融资项目',
          key: 'financingFlag',
          // component: 'select',
          // optionsKey: 'isFinancingProject',
          component: 'radio',
          options: ['是', '否'],
          visible: true
        },
        {
          groupName: '项目诉求',
          tag: 'new',
          label: '其他需求',
          key: 'otherNeeds',
          component: 'input',
          visible: true
        },
        {
          groupName: '项目诉求',
          tag: 'new',
          label: '达产后5年预计产值(万元)', // 数字
          key: 'estimatedOutput',
          component: 'input',
          type: 'number',
          visible: true
        },

        // 其他字段
        // {
        //   label: '项目状态',
        //   key: 'projectState',
        //   component: 'select',
        //   optionsKey: 'projectStageTypeOptions',
        //   visible: true
        // },
        // 时间相关字段 项目进展时间
        {
          groupName: '项目进展时间',
          label: '预计完成商务洽谈时间',
          key: 'planBusinessFinishTime',
          component: 'date',
          visible: true
        },
        {
          groupName: '项目进展时间',
          label: '预计完成上会流程时间',
          key: 'planMeetTime',
          component: 'date',
          visible: true
        },
        {
          groupName: '项目进展时间',
          label: '预计签约时间',
          key: 'planSignTime',
          component: 'date',
          visible: true
        },
        {
          groupName: '项目进展时间',
          label: '实际签约时间',
          key: 'actuallySignTime',
          component: 'date',
          visible: true
        },
        {
          groupName: '项目进展时间',
          label: '预计入驻/拿地时间',
          key: 'planInTime',
          component: 'date',
          visible: true
        },
        {
          groupName: '项目进展时间',
          label: '实际入驻/拿地时间',
          key: 'actuallyInTime',
          component: 'date',
          visible: true
        },
        {
          groupName: '项目进展时间',
          label: '备注',
          key: 'remarks',
          component: 'input',
          type: 'textarea',
          rows: 3,
          visible: true
        }
      ],
      fileList: [],
      canDaoChu: false,
      leaveTimer: null
    }
  },
  computed: {
    titles() {
      return [this.title]
    },
    projectStageOptions() {
      return projectStageOptions
    },
    industryTypeOptions() {
      return industryTypeOptions
    },
    propertyOptions() {
      return propertyOptions
    },
    industrialChainOptions() {
      return industrialChainOptions
    },
    projectOriginalOptions() {
      return projectOriginalOptions
    },
    otherApplyImportantArea() {
      return otherApplyImportantArea
    },
    isImportantProject() {
      return isImportantProject
    },
    isFinancingProject() {
      return isFinancingProject
    },
    projectLevelOptions() {
      return projectLevelOptions
    },
    otherIndustrialType() {
      return otherIndustrialType
    },
    investTypeOptions() {
      return investTypeOptions
    },
    landingTypeOptions() {
      return landingTypeOptions
    },
    projectStageTypeOptions() {
      return projectStageTypeOptions
    },

    // 统一分组后的表单字段
    groupedFormFields() {
      const visibleFields = this.formFields.filter(
        (field) => {
          // 根据字段key判断条件显示
          if (field.key === 'linkSourcePId') {
            return this.basicForm.linkSource === '链属'
          }
          if (
            field.key === 'landingArea' ||
            field.key === 'relatedProjectId'
          ) {
            return this.basicForm.landingType === '拿地'
          }
          if (
            field.key === 'carrierArea' ||
            field.key === 'settledCarrier'
          ) {
            return ['入驻载体', '租赁厂房'].includes(
              this.basicForm.landingType
            )
          }
          return field.visible
        }
      )

      // const result = []
      // for (let i = 0; i < visibleFields.length; i += 3) {
      //   result.push(visibleFields.slice(i, i + 3))
      // }
      const result = visibleFields.reduce((acc, cur) => {
        if (acc[cur.groupName]) {
          acc[cur.groupName].push(cur)
        } else {
          acc[cur.groupName] = [cur]
        }
        return acc
      }, {})

      return result
    }
  },
  watch: {
    // 监听基本信息的项目阶段变化，同步更新进度信息第一条
    'basicForm.stage'(newStage) {
      if (this.progressList.length > 0) {
        this.$set(this.progressList[0], 'stage', newStage)
        this.$forceUpdate()
      }
    },
    // 监听基本信息的属性变化，同步更新进度信息第一条
    'basicForm.property'(newProperty) {
      if (this.progressList.length > 0) {
        this.$set(
          this.progressList[0],
          'property',
          newProperty
        )
        this.$forceUpdate()
      }
    },
    'basicForm.linkSource'(newLinkSource) {
      if (newLinkSource === '链属') {
        this.getChainMasterOptions()
      }
    },
    'basicForm.landingType'(newLandingType) {
      if (newLandingType === '拿地') {
        // this.getRelatedProjectOptions()
      } else if (newLandingType === '入驻载体') {
        // this.getSettledCarrierOptions()
      }
    },
    basicForm: {
      handler(newVal, oldVal) {
        if (this.isBasicFormReady === true) {
          this.isBasicFormChanged = true
          console.log('basicForm changed')
        }
      },
      deep: true
    }
  },
  mounted() {
    instance = this

    this.getManagerOptions()
    this.getRelatedProjectOptions()
    this.getSettledCarrierOptions()
    this.getEnterpriseOptions()
    // this.getChainMasterOptions()
    if (this.isEdit) {
      this.getDetailInfo()
    } else {
      setTimeout(() => {
        this.isBasicFormReady = true
        this.isBasicFormChanged = false
      }, 500)
    }
  },
  beforeRouteLeave(to, from, next) {
    if (!this.isBasicFormChanged) {
      next()
    } else {
      if (to.path !== '/login') {
        this.leaveTimer = setTimeout(() => {
          this.$confirm('信息未保存，确认退出?', '注意', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              next()
            })
            .catch(() => {
              next(false)
            })
        }, 100)
      } else {
        if (this.leaveTimer) {
          clearTimeout(this.leaveTimer)
        }
        next(true)
      }
    }
  },
  methods: {
    isFormItemDisabled(field) {
      this.isExisting = this.enterpriseOptions.some(
        (item) =>
          item.name === this.basicForm.name &&
          item.socialCode === this.basicForm.socialCode
      )
      return (
        this.isDetail ||
        (field.key === 'socialCode' && this.isExisting)
      )
    },
    // 切换tab
    handleChangeTab(item, index) {
      this.currentTab = index
    },
    // 获取项目详情
    getDetailInfo() {
      this.loading = true
      queryInvestInfoById(this.pkid)
        .then((res) => {
          if (res.success) {
            this.basicForm = res.data
            this.progressList =
              this.basicForm.padBusinessProjectProcessRelList
            this.basicForm.projectStarLevel = this.basicForm
              .projectStarLevel
              ? Number(this.basicForm.projectStarLevel)
              : 0
            if (this.basicForm.projectTopLevel) {
              this.basicForm.projectTopLevel =
                this.basicForm.projectTopLevel.split(',')
            } else {
              this.basicForm.projectTopLevel = []
            }

            if (this.basicForm.productCategory) {
              this.basicForm.productCategory =
                this.basicForm.productCategory.split(',')
            } else {
              this.basicForm.productCategory = []
            }

            if (this.basicForm.settledCarrier) {
              // 将保存的路径字符串转换回数组格式
              this.basicForm.settledCarrier =
                this.basicForm.settledCarrier.split(',')
            } else {
              this.basicForm.settledCarrier = []
            }

            if (this.basicForm.linkSourcePId) {
              this.basicForm.linkSourcePId =
                this.basicForm.linkSourcePId.split(',')
            } else {
              this.basicForm.linkSourcePId = []
            }
            // 确保基本信息和进度信息第一条保持一致
            this.syncBasicWithFirstProgress()
          }
        })
        .finally(() => {
          this.loading = false
          this.isBasicFormReady = true
        })
    },

    // 保存信息
    saveInfo() {
      this.$refs.basicFormRef.validate((res) => {
        if (res) {
          if (this.basicForm.projectTopLevel.length) {
            this.basicForm.projectTopLevel =
              this.basicForm.projectTopLevel.join(',')
          } else {
            this.basicForm.projectTopLevel = ''
          }
          if (this.basicForm.productCategory.length) {
            this.basicForm.productCategory =
              this.basicForm.productCategory.join(',')
          } else {
            this.basicForm.productCategory = ''
          }
          if (this.basicForm.settledCarrier.length) {
            this.basicForm.settledCarrier =
              this.basicForm.settledCarrier.join(',')
          } else {
            this.basicForm.settledCarrier = ''
          }
          if (
            this.basicForm.linkSource == '链属' &&
            this.basicForm.linkSourcePId.length
          ) {
            this.basicForm.linkSourcePId =
              this.basicForm.linkSourcePId.join(',')
          } else {
            this.basicForm.linkSourcePId = ''
          }
          // if (this.basicForm.address.length) {
          //   this.basicForm.address = this.basicForm.address.join(',')
          // }
          this.basicForm.padBusinessProjectProcessRelList =
            this.progressList
          this.basicForm.planBusinessFinishTime =
            this.setDateFormat(
              this.basicForm.planBusinessFinishTime
            )
          this.basicForm.planMeetTime = this.setDateFormat(
            this.basicForm.planMeetTime
          )
          this.basicForm.planSignTime = this.setDateFormat(
            this.basicForm.planSignTime
          )
          this.basicForm.actuallySignTime =
            this.setDateFormat(
              this.basicForm.actuallySignTime
            )
          this.basicForm.planInTime = this.setDateFormat(
            this.basicForm.planInTime
          )
          this.basicForm.actuallyInTime =
            this.setDateFormat(
              this.basicForm.actuallyInTime
            )

          const params = {
            ...this.basicForm,
            fileList: this.fileList,
            projectState: '' // 项目状态 去掉
          }
          console.log(
            'saveinfo file list: ',
            params,
            this.fileList
          )

          addInvestInfo(params).then((res) => {
            if (res.success) {
              this.isBasicFormChanged = false
              this.$message.success('保存成功')
              this.$router.push({
                path: '/dataManagement/projectManagement/investProjectInfo/list',
                query: { refresh: Date.now() }
              })
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },

    getManagerOptions() {
      const params = {
        pageIndex: 1,
        pageSize: 999
      }
      userQuery(params).then((res) => {
        this.managerOptions = res.data.list
          .filter((item) => item.deptName === DEPT_NAME)
          .map((i) => i.userName)
      })
    },
    getEnterpriseOptions() {
      enterpriseInfoQuery({
        pageIndex: 1,
        pageSize: 999
      }).then((res) => {
        if (res.success) {
          this.enterpriseOptions = res.data.list.map(
            (item) => {
              return {
                ...item,
                label: item.name,
                value: item.name
              }
            }
          )
        }
      })
    },
    // 链主企业选项
    getChainMasterOptions() {
      const params = {
        linkSource: '链主'
      }
      queryChainMasterOptions(params).then((res) => {
        this.chainMasterOptions = res.data.map((item) => {
          return {
            label: item.projectName,
            value: item.pkid
          }
        })
      })
    },

    // 关联项目选项
    getRelatedProjectOptions() {
      const params = {
        pageIndex: 1,
        pageSize: 999
      }
      // this.loading = true
      queryConstructionProject(params)
        .then((res) => {
          this.relatedProjectOptions = res.data.list.map(
            (item) => {
              return {
                label: item.name,
                value: item.pkid
              }
            }
          )
          // this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    // 拟入驻载体选项
    getSettledCarrierOptions() {
      // this.loading = true
      querySettledCarrier()
        .then((res) => {
          this.settledCarrierOptions = res.data
          // this.loading = false
        })
        .catch(() => {
          // this.loading = false
        })
    },

    setDateFormat(date) {
      if (date) {
        return dayjs(date).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },

    handleSubmit(data) {
      if (this.editIndex > -1) {
        // 编辑现有进度信息
        this.progressList[this.editIndex] = data

        // 如果编辑的是第一条，需要同步基本信息
        if (this.editIndex === 0) {
          this.basicForm.stage = data.stage
          this.basicForm.property = data.property
        }
      } else {
        // 新增进度信息，插入到最前面成为第一条
        this.progressList.unshift(data)

        // 新增的进度信息成为第一条，同步基本信息
        this.basicForm.stage = data.stage
        this.basicForm.property = data.property
      }
    },

    editProgress(item, index) {
      this.showDialog = true
      this.editIndex = index
      this.currentData = cloneDeep(item)
      this.currentInfo = {
        stage: item.stage
          ? item.stage
          : this.basicForm.stage,
        property: item.property
          ? item.property
          : this.basicForm.property
      }
    },

    deleteProgress(index) {
      // 如果删除的是第一条，且还有其他进度信息，需要更新基本信息为新的第一条
      if (index === 0 && this.progressList.length > 1) {
        const newFirstItem = this.progressList[1]
        this.basicForm.stage =
          newFirstItem.stage || this.basicForm.stage
        this.basicForm.property =
          newFirstItem.property || this.basicForm.property
      }

      this.progressList.splice(index, 1)
    },

    addProcess() {
      this.showDialog = true
      this.currentInfo = {
        stage: this.basicForm.stage,
        property: this.basicForm.property
      }
      this.currentData = {
        stage: '',
        property: '',
        createTime: '',
        newestProcess: '',
        problemFlag: '是',
        problemContent: '',
        solveAdvice: ''
      }
      this.editIndex = -1
    },

    syncBasicWithFirstProgress() {
      if (this.progressList.length > 0) {
        const firstProgress = this.progressList[0]
        if (firstProgress.stage) {
          this.basicForm.stage = firstProgress.stage
        } else if (this.basicForm.stage) {
          this.$set(
            this.progressList[0],
            'stage',
            this.basicForm.stage
          )
        }

        if (firstProgress.property) {
          this.basicForm.property = firstProgress.property
        } else if (this.basicForm.property) {
          this.$set(
            this.progressList[0],
            'property',
            this.basicForm.property
          )
        }
      }
    },

    onBasicStageChange(stage) {
      if (this.progressList.length > 0) {
        this.$set(this.progressList[0], 'stage', stage)
        this.$forceUpdate()
      }
    },

    onBasicPropertyChange(property) {
      if (this.progressList.length > 0) {
        this.$set(
          this.progressList[0],
          'property',
          property
        )
        this.$forceUpdate()
      }
    },

    onEnterpriseNameChange(val) {
      console.log('enterpriseNameChange', val)
      const value = String(val).trim()
      this.isExisting = this.enterpriseOptions.some(
        (item) => item.name === value
      )

      if (!this.isExisting) {
        this.basicForm.name = value
        this.basicForm.socialCode = ''
        this.basicForm.registerTime = ''
        this.basicForm.registerMoney = ''
        this.basicForm.enterpriseId = ''
        this.basicForm.valuation = ''
      } else {
        // 选择现有企业
        // this.manualInputName = ''
        const enterpriseInfo = this.enterpriseOptions.find(
          (item) => item.name === value
        )
        console.log('enterpriseInfo', enterpriseInfo)
        this.basicForm.socialCode =
          enterpriseInfo.socialCode
        this.basicForm.name = enterpriseInfo.name
        this.basicForm.address =
          enterpriseInfo.registerAddress
        this.basicForm.enterpriseId = enterpriseInfo.pkid
        this.basicForm.projectTopLevel =
          enterpriseInfo.projectTopLevel.split(',') || []
        this.basicForm.valuation =
          enterpriseInfo.valuation || ''
        this.basicForm.contract =
          enterpriseInfo.leader || ''
        this.basicForm.telephone =
          enterpriseInfo.contract || ''
        this.basicForm.companyBackgroud =
          enterpriseInfo.messageContent || ''
        this.basicForm.registerTime =
          enterpriseInfo.registerTime
        this.basicForm.registerMoney =
          enterpriseInfo.registerMoney
      }
    },

    // 重置editIndex
    resetEditIndex() {
      this.editIndex = -1
    },

    // 获取字段选项
    getOptions(optionsKey) {
      const optionsMap = {
        projectStageOptions: this.projectStageOptions,
        propertyOptions: this.propertyOptions,
        projectOriginalOptions: this.projectOriginalOptions,
        industryTypeOptions: this.industryTypeOptions,
        industrialChainOptions: this.industrialChainOptions,
        otherIndustrialType: this.otherIndustrialType,
        investTypeOptions: this.investTypeOptions,
        isFinancingProject: this.isFinancingProject,
        isImportantProject: this.isImportantProject,
        projectLevelOptions: this.projectLevelOptions,
        landingTypeOptions: this.landingTypeOptions,
        chainMasterOptions: this.chainMasterOptions,
        relatedProjectOptions: this.relatedProjectOptions,
        enterpriseOptions: this.enterpriseOptions,
        settledCarrierOptions: this.settledCarrierOptions,
        managerOptions: this.managerOptions,
        projectStageTypeOptions:
          this.projectStageTypeOptions
      }
      return optionsMap[optionsKey] || []
    },

    // 处理字段变化
    handleFieldChange(fieldKey, value) {
      // 如果是项目阶段变化，调用原有的处理方法
      if (fieldKey === 'stage') {
        this.onBasicStageChange(value)
      }
      // 如果是属性变化，调用原有的处理方法
      if (fieldKey === 'property') {
        this.onBasicPropertyChange(value)
      }

      if (fieldKey === 'name') {
        this.onEnterpriseNameChange(value)
      }
    },

    changeFile(list) {
      console.log('父组件获得了值', list)
      this.fileList = list
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .body {
    display: flex;
    padding: 10px 20px 0 20px;

    &-left {
      width: 70%;
      border-right: 1px solid #f1f1f1;
      overflow: scroll;
    }

    &-right {
      flex: 1;
      padding-left: 10px;
    }

    .top {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      padding-right: 10px;
    }
  }

  .tabs {
    width: 100%;
    height: 50px;
    border-bottom: 1px solid #f1f1f1;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    &-item {
      display: flex;
      align-items: center;
      justify-content: center;
      min-width: 200px;
      height: 100%;
      font-size: 16px;
      font-weight: 500;
      color: #4c565c;
      position: relative;
      cursor: pointer;

      &::before {
        position: absolute;
        content: ' ';
        right: 0;
        top: 19px;
        width: 1px;
        height: 12px;
        background: #d0d8e1;
      }

      &:last-child {
        &::before {
          display: none;
        }
      }

      &.active {
        color: #497fa3;

        &::after {
          position: absolute;
          content: ' ';
          bottom: 0;
          left: 86px;
          width: 26px;
          height: 3px;
          background: #497fa3;
          border-radius: 2px;
        }
      }
    }
  }

  .line {
    display: flex;
    justify-content: center;
  }
}
// :deep(.el-form-item.change) {
//   .el-form-item__label {
//     color: #409EFF,
//   }
// }
// :deep(.el-form-item.new) {
//   .el-form-item__label {
//     color: #F56C6C,
//   }
// }
</style>
